<template>
  <el-container>
    <el-header>
      <el-menu :default-active="activeIndex2" class="el-menu-demo" mode="horizontal" @select="handleSelect"
               background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
        <el-menu-item index="1">处理中心</el-menu-item>
        <el-submenu index="2">
          <template slot="title">Welcome</template>
          <el-menu-item index="/Map">地图</el-menu-item>
          <el-menu-item index="2-2">选项2</el-menu-item>
          <el-menu-item index="2-3">选项3</el-menu-item>
          <el-submenu index="2-4">
            <template slot="title">选项4</template>
            <el-menu-item index="2-4-1">选项1</el-menu-item>
          </el-submenu>
        </el-submenu>
        <el-menu-item index="3">
          <el-badge :value="massages.length" :max="99">消息中心</el-badge>
        </el-menu-item>
        <el-menu-item index="4"><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item>
      </el-menu>
    </el-header>
    <el-main>
      <el-container>
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="massage"></el-input>
        <el-button type="primary" plain @click="send">发送消息</el-button>
        <el-button type="primary" plain @click="socketInit">连接</el-button>
        <el-button type="danger" plain @click="closeWebSocket">关闭WebSocket连接</el-button>
        <el-button type="danger" plain @click="signOut">退出登录</el-button>
      </el-container>
      <div>
        <el-card class="box-card">
          <el-alert style="margin-bottom: 10px;width: 100%" v-for="(msg,index)  in massages " :key="index" :title="msg"
                    type="warning" close-text="√"></el-alert>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "SocketRoom",
  data() {
    return {
      webSocket: {},
      massage: '',
      massages: [],
      activeIndex: '1',
      activeIndex2: '1'
    }
  },
  created() {
  },
  methods: {
    async signOut() {
      let self = this;
      let response = await self.$service.signOut();
      if (response.code === 200) {
        self.success(response.message);
      } else {
        self.error(response.message);
      }
      await self.$router.push({path: '/'})
    },
    socketInit() {
      // 取用
      let self = this;
      //判断当前浏览器是否支持WebSocket
      if ('WebSocket' in window) {
        //改成你的地址
        self.webSocket = new WebSocket("ws://localhost/api/websocket/" + sessionStorage.getItem("token"));
      } else {
        self.error('当前浏览器 Not support websocket')
      }
      //连接发生错误的回调方法
      self.webSocket.onerror = function () {
        self.error("WebSocket连接发生错误");
      };

      //连接成功建立的回调方法
      self.webSocket.onopen = function () {
        self.success("聊天室连接成功");
      }
      //接收到消息的回调方法
      self.webSocket.onmessage = function (event) {
        self.success(event.data);
      }

      //连接关闭的回调方法
      self.webSocket.onclose = function () {
        self.error("聊天室连接关闭");
      }
      //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = function () {
        self.closeWebSocket();
      }

    },
    //关闭WebSocket连接
    closeWebSocket() {
      let self = this;
      self.webSocket.close();
    },
    //发送消息
    send() {
      let self = this;
      if (self.massage) {
        let token = sessionStorage.getItem("token");
        let obj = {msg: self.massage, token: token}
        self.webSocket.send(JSON.stringify(obj));
        self.massages.push(self.massage)
      }
    },
    async handleSelect(key, keyPath) {
      let self = this;
      await self.$router.push({path: keyPath[1]})
    },
    success(massage) {
      this.$message({
        message: massage,
        type: 'success'
      });
    },
    error(massage) {
      this.$message({
        message: massage,
        type: 'error'
      });
    }
  }
}
</script>

<style scoped>
.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
